
//
// 120524 - AH - (Aura) Created.
// 150626a- AH - (Huset) Missing java doc.
// 120626b- AH - (Huset) Took CE_ID in use.
// 120728 - AH - Responds with array not list as used to.
//

package org.soekrat.server.servlets.semanticeffects;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.soekrat.server.io.db.ConversationElement;
import org.soekrat.server.io.db.SemanticEffect;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.serialization.SemanticEffectSerializable;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;

/**
 * <p>
 *   Implements request to get a semantic effects for a given conversation
 *   element.
 * </p>
 * @author Arne Halvorsen (AH)
 * @author Laetitia Le Chatton (LLC)
 */
@SuppressWarnings("serial")
public final class GetSemanticEffectsHttpServlet 
  extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public GetSemanticEffectsHttpServlet(){}

  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res);
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
    }
    else
    {
      if (!validate(res, def, req)) return;
      
      long ceId=def.fetch(CE_ID.name(), req).getLongValue();
      
      SoekratDAO dao=new SoekratDAOFactory().create();
      
      ConversationElement ce=dao.getConversationElement(ceId);
      if (ce==null)
      {
        respond(res, "no conversation element for ce-id : "+ceId);
        return;
      }
      
      List<SemanticEffect> effects=dao.getSemanticEffects(ce);
      
      List<SemanticEffectSerializable> ser=
        new ArrayList<SemanticEffectSerializable>();
      
      for (SemanticEffect curr : effects) 
      {
        ser.add(new SemanticEffectSerializable(curr));  
      }
      
      respond(res, ser.toArray(SemanticEffectSerializable.EMPTY_ARRAY));
    }
    
  }

  @Override
  public HttpRequestDef getHttpRequestDef() 
  {
    return new HttpRequestDef("/soekrat_server/get-semantic-effects")
      .desc("Gets Semantic Effects For A Convesation Element").parameter(CE_ID);
  }
  
}
